<template>
  <qx-table :option="tableOption" :remoteData="remoteData">
    <template v-slot:top>
      <qx-form v-model="searchForm" :option="tableOption" isSearch @submit="startSearch"></qx-form>
    </template>
    <template v-slot:menuLeft>
      <q-btn color="primary" icon="add" unelevated @click="handleCreate">
        {{ $t('Add') }}
      </q-btn>
      <q-btn outline text-color="primary" @click="handleSync('rcs', $t('Misc.SynchronizeRCSData'))">
        {{ $t('Misc.SynchronizeRCSData') }}
      </q-btn>
      <q-btn outline text-color="primary" @click="handleSync('toRcs', $t('Misc.SynchronizeToRCS'))">
        {{ $t('Misc.SynchronizeToRCS') }}
      </q-btn>
      <q-import :errorParam="['AGV_MAS_DATA', 'importAgvMasDataShelfManagement']"
                downUrl="/yfagv/api/agvMasDataShelfManagement/importInfoTemplate"
                importUrl="/yfagv/api/agvMasDataShelfManagement/importInfo" @import-after="startSearch"></q-import>
    </template>
    <template v-slot:menu="{ row }">
      <q-btn class="col" color="primary" icon="mdi-square-edit-outline" outline unelevated @click="handleUpdate(row)">
        {{ $t('Edit') }}
      </q-btn>
      <q-btn class="col" color="primary" icon="delete" outline unelevated @click="handleDelete(row)">
        {{ $t('Del') }}
      </q-btn>
    </template>
  </qx-table>
  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" btnAlign="center"
           position="right" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="tableOption"></qx-form>
  </q-modal>
  <q-modal v-model="syncModelVisible" :header="header" width="400" @beforeClose="beforeClose" @confirm="submitSync">
    <qx-form ref="FormRef" v-model="formInfo" :option="syncOption"></qx-form>
  </q-modal>
</template>
<script setup>
import { i18n, toI18nName } from 'boot/i18n.js'
import { deleteAPI, postAPI, putAPI } from 'src/api/index.js'
import { getRemoteData, setRemoteData } from 'src/enum/ajaxRemoteData.js'
import { computed, onMounted, ref } from 'vue'
import { createDialog, deepClone } from 'src/utils/utils.js'

const header = ref('')
const formInfo = ref({})
const rackType = ref([])
const FormRef = ref(null)
const AGVBrands = ref([])
const searchForm = ref({})
const modalVisible = ref(false)
const syncModelVisible = ref(false)
const remoteData = ref({ dicUrl: '/yfagv/api/agvMasDataShelfManagement/list' })
getRemoteData('agv_brand', '/yfagv/api/agvCfgBrand/list').then(data => (AGVBrands.value = data))
getRemoteData('rack_type', '/yfagv/api/agvMasDataShelfBase/list').then(data => (rackType.value = data))
const brandProps = computed(() => ({ label: `${toI18nName('agvBrandNameZhCn')}`, value: 'agvBrandCode' }))
const syncOption = computed(() => {
  return {
    span: 22, labelWidth: 90,
    column: [{
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      props: brandProps.value, required: true
    }]
  }
})
const tableOption = computed(() => {
  return {
    grid: true, span: 22, export: true, labelWidth: 100, headerWidth: 60, searchSpan: 5,
    column: [{
      label: `${i18n.t('CarrierCore.RackCode')}`, field: 'shelfNo', minWidth: 100, required: true, hide: true,
      readonly: !!formInfo.value.id, topLeft: true
    }, {
      label: `${i18n.t('CarrierCore.RackType')}`, field: 'shelfTypeId', type: 'select', options: rackType.value,
      minWidth: 100, props: { label: 'shelfTypeName', value: 'id' }, required: true,
      format: (_, row) => `${row.shelfTypeNo || ''}_${row.shelfTypeName || ''}`
    }, {
      label: `${i18n.t('CarrierCore.RackDescription')}`, field: 'shelfDesc', type: 'textarea',
      minWidth: 100, maxlength: 500, search: false
    }, {
      label: `${i18n.t('CreationTime')}`, field: 'createdTime', required: true, minWidth: 70,
      search: false, display: false
    }]
  }
})

const handleCreate = () => {
  modalVisible.value = true
}
const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}
const handleSync = (source, title) => {
  header.value = title
  formInfo.value = { source }
  const msg = source === 'rcs' ? `${i18n.t('Misc.SyncTip1')}` : `${i18n.t('Misc.SyncTip2')}`
  createDialog({ msg }, () => {
    syncModelVisible.value = true
  }, () => {})
}
const handleDelete = row => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/yfagv/api/agvMasDataShelfManagement/${row.id}`, {}, () => startSearch())
  }, () => {})
}
const formatSearchForm = () => ({ ...searchForm.value })
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
  action === 'clear' && setRemoteData('agv_rack')
}
const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  modalVisible.value = false
  syncModelVisible.value = false
}
const submitForm = (mDone) => {
  FormRef.value.validate((form, done) => {
    const API = form.id ? putAPI : postAPI
    API('/yfagv/api/agvMasDataShelfManagement', form, () => {
      startSearch('clear')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
const submitSync = mDone => {
  FormRef.value.validate((form, done) => {
    const uri = form.source === 'rcs' ? '/yfagv/api/syncRcsToFactoryApi/syncAgvMasDataShelfPositionManagement'
      : '/yfagv/api/syncRcsApi/syncAgvMasDataShelfPosition'
    postAPI(uri, form, () => {
      form.source === 'rcs' && startSearch('clear')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}

onMounted(startSearch)
</script>